package cn.minicloud;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class BackendSession {
    private static final Logger logger = LoggerFactory.getLogger(BackendSession.class);

    private Channel backendChannel;
    private final String host;
    private final int port;
    private final Channel clientChannel;

    public BackendSession(String backendAddr, Channel clientChannel) {
        String[] parts = backendAddr.split(":");
        this.host = parts[0];
        this.port = Integer.parseInt(parts[1]);
        this.clientChannel = clientChannel;
    }

    public void connectAndStartForwarding() {
        EventLoopGroup group = new NioEventLoopGroup(1);
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) {
                        ch.pipeline().addLast(new ProxyBackendHandler(clientChannel));
                    }
                });
            ChannelFuture f = b.connect(host, port).sync();
            backendChannel = f.channel();
            // Add frontend proxy handler to client pipeline
            clientChannel.pipeline().addLast(new ProxyFrontendHandler(backendChannel));
            logger.info("Connected to backend MySQL {}:{} and set up proxy forwarding", host, port);
        } catch (Exception e) {
            logger.error("Failed to connect to backend {}:{}", host, port, e);
        }
    }
}
